package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Result;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.pojoExt.EmployeeExt;
import com.ruan.pojoExt.ProjectExt;
import com.ruan.pojoExt.TaskExt;
import com.ruan.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.ruan.pojo.Project.CompletionStatus.onGoing;

@Slf4j
@Service//交由spring容器进行管理//  mybatis-plus提供的规范，继承父类，实现父接口
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private TasksService taskService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ProjectAssignmentsMapper projectAssignmentsMapper;

    @Autowired
    private ParticipantMapper participantMapper;

    @Autowired
    private ParticipantService participantService;

    @Autowired
    private TasksMapper tasksMapper;

    @Autowired
    private ClientService clientService;

    @Autowired
    private FileMapper fileEntityMapper;

    @Autowired
    private FileService fileEntityService;

    @Override
    public List<ProjectExt> getTodayProjects(String employeeId) {
//        LocalDate currentDate = LocalDate.now();
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
//        System.out.println("employeeId是"+employeeId);
        queryWrapper.eq(Project::getEmployeeId, employeeId);

        // 从数据库中获取该员工(项目经理)今天未完成的项目
        queryWrapper.eq(Project::getEmployeeId, employeeId)
                .ge(Project::getEndDate, LocalDate.now())
                // 获取截止时间大于等于当前日期的任务
                .ne(Project::getCompletionStatus, Project.CompletionStatus.completed);
        queryWrapper.orderByDesc(Project::getEndDate);
        // 获取completeStatus不为completed的项目
        List<Project> projectList = projectMapper.selectList(queryWrapper);
        List<ProjectExt> projectExtList = new ArrayList();
        for(Project project : projectList){
            ProjectExt projectExt = new ProjectExt();
            BeanUtils.copyProperties(project,projectExt);

//            Client client = clientService.getById(project.getClientId());
//            if(client!=null){
//                projectExt.setClientName(client.getName());
//            }

//            LambdaQueryWrapper<Participant> queryWrapper1 = new LambdaQueryWrapper<>();
//            queryWrapper1.eq(Participant::getProjectId,project.getId());
//            List<Participant> participantList = participantMapper.selectList(queryWrapper1);

//            List<Long> employeeIds = new ArrayList<>();
//            for(Participant participant : participantList) {
//                LambdaQueryWrapper<Tasks> queryWrapper2 = new LambdaQueryWrapper();
//                //TODO
//                queryWrapper2.eq(Tasks::getEmployeeId, participant.getEmployeeId())//已经有任务的组员就不提醒了
//                        .ge(Tasks::getDate, currentDate); // 获取截止时间大于等于当前日期的任务
//                List<Tasks> tasksList = tasksMapper.selectList(queryWrapper2);
//
//                for (Tasks tasks : tasksList) {
//                    employeeIds.add(tasks.getEmployeeId());
//                }
//
//            }
            //System.out.println("employeeIds有当前时间没有任务的参与人员的id吗"+employeeIds);
            //获取当前时间没有任务的参与人员
//            queryWrapper1.notIn(employeeIds.size() > 0 && employeeIds.size() > 0,
//                    Participant::getEmployeeId,employeeIds);

//            List<Participant> participantListWithOutTask = participantMapper.selectList(queryWrapper1);
//            List<Employee> employeeList = new ArrayList<>();
//            for(Participant participant : participantListWithOutTask){
////                Employee employee = employeeService.getById(participant.getEmployeeId());
//               LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper();
//                queryWrapper2.eq(Employee::getId,participant.getEmployeeId())
//                                .notIn(Employee::getStatus,"离职","待审核");
//                Integer count = employeeMapper.selectCount(queryWrapper2);
//                if(count>0){
//                    re
//                }
//                Employee employee = employeeMapper.selectOne(queryWrapper2);
////                System.out.println("employee的状态是"+employee);
//                if(employee!=null){//防止把空的也存入
//                    employeeList.add(employee);
//                }
//            }
//            projectExt.setEmployeeList(employeeList);
            projectExtList.add(projectExt);
        }
        return projectExtList;
    }


     /**
     * 将项目信息导出为Excel
     * @throws Exception
     * @return
     */
    @Override
    public byte[] exportToExcel(Integer id) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper();
        if (id == null) {
            // 如果 id 为 null，查询所有项目
            queryWrapper = null;
            //log.info("查询所有项目");
        } else {
            // 如果 id 有值，添加相应的查询条件
            //log.info("查询id为{}的员工负责的项目", id);
            queryWrapper.eq(Project::getEmployeeId, id);
        }
        List<Project> projectList = projectMapper.selectList(queryWrapper);
//        为在调用PoiUtils类的exportClientInfo方法时，该方法是非静态方法，
//        而你是通过类名直接调用的，需要先创建PoiUtils对象再调用该方法。
//        PoiUtils poiUtils = new PoiUtils();
//        poiUtils.exportClientInfo(clientList);

//        log.info("查询到{}条项目", projectList.size());
//        if(projectList.size() == 0){
            //没有查到符合条件的项目
//            return null;
//        }
//        log.info("开始导出项目信息");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //工作簿，允许您在Java应用程序中创建、读取和修改Excel文件
        XSSFWorkbook excel=new XSSFWorkbook();
        //创建一个工作表对象
        XSSFSheet sheet = excel.createSheet("sheet1");


        String[] headers = {"项目编号","对接客户","项目名", "负责人",
                "项目内容", "截止日期",
                "创建时间","更新时间","完成时间"
                ,"完成状态","总金额","单位"};

        XSSFRow row1 = sheet.createRow(0);

        for (int i = 0; i < headers.length; i++) {
            row1.createCell(i).setCellValue(headers[i]);
        }

        for (int i = 0; i < projectList.size(); i++) {
            Project project = projectList.get(i);
//            LocalDateTime endDate = project.getEndDate();
            String endDate = String.valueOf(project.getEndDate());
            if(project.getEndDate() != null){
                // 解析字符串为 LocalDateTime
                LocalDateTime dateTime = LocalDateTime.parse(endDate);
                // 格式化为只包含日期部分的字符串
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                endDate = dateTime.format(formatter);
            }

            LocalDateTime createTime = project.getCreateTime();
            LocalDateTime updateTime = project.getUpdateTime();
            LocalDateTime completionTime = project.getCompletionTime();


            XSSFRow row2 = sheet.createRow(i+1);

            Project.CompletionStatus completeStatus = project.getCompletionStatus();
//            String completeStatusText = (completeStatus == onGoing) ? "进行中" : "已完成";
            String completeStatusText = null;
            if(completeStatus == Project.CompletionStatus.inPreparation){
                completeStatusText = "待开始";
            }else if(completeStatus == Project.CompletionStatus.onGoing){
                completeStatusText = "施工中";
            }else if(completeStatus == Project.CompletionStatus.deBugging){
                completeStatusText = "调试中";
            }else if(completeStatus == Project.CompletionStatus.waitForCheck){
                completeStatusText = "待验收";
            }else{
                completeStatusText = "已完成";
            }

//            int payStatus = project.getPayStatus();
//            String payStatusText = (payStatus == 0) ? "待付款" : (payStatus == 1) ? "已付款" : "已取消";
//
//            int payMethod = project.getPayMethod();
//            String payMethodText = (payMethod == 0) ? "银行卡" : (payMethod == 1) ? "微信" : "支付宝";

            Client client = null;
            Employee employee = null;

            if(project != null){
                if(project.getClientId() != null) {
                    client = clientService.getById(project.getClientId());//报空指针。。。。。。
                }
                if(project.getEmployeeId() != null) {
                    employee = employeeService.getById(project.getEmployeeId());//报空指针。。。。。。啊啊啊啊
                }

                String[] projectInfo = {
                        project.getPid(),client != null && client.getName()!=null ? client.getName() : "",
                        project.getProjectName(),
                        employee != null && employee.getName()!=null ? employee.getName() : "",
                        project.getDescription(),
                        project.getEndDate() != null ? endDate: "",
                        String.valueOf(createTime), String.valueOf(updateTime),
                        project.getCompletionTime() != null ? String.valueOf(completionTime) : "",
                        completeStatusText,
                        project.getActualAmount() != null ? String.valueOf(project.getActualAmount()) : "",
                        project.getCurrency() != null ? String.valueOf(project.getCurrency()) : ""
                };

                for (int j = 0; j < projectInfo.length; j++) {
                    row2.createCell(j).setCellValue(projectInfo[j]);
                }
            }
        }

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.setContentDispositionFormData("attachment","项目表.xlsx");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            excel.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();

    }

    /**
     * 删除项目操作
     * @param id 项目id
     * @return
     */
    @Override
    @Transactional
    public Boolean deleteProject(Integer id) {
//        LambdaQueryWrapper<Project> projectQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<ProjectAssignments> projectAssignmentsQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<ProjectToolAssignment> projectToolAssignmentQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<Participant> participantQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<FileEntity> fileEntityQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<Tasks> tasksQueryWrapper = new LambdaQueryWrapper();

//        projectQueryWrapper.eq(Project::getId,id);
//        Project project = projectMapper.selectOne(projectQueryWrapper);

        Project project = projectMapper.selectById(id);
        if (project!=null){
            projectAssignmentsQueryWrapper.eq(ProjectAssignments::getProjectId,project.getId());
            projectToolAssignmentQueryWrapper.eq(ProjectToolAssignment::getProjectId,project.getId());
            participantQueryWrapper.eq(Participant::getProjectId,project.getId());
            fileEntityQueryWrapper.eq(FileEntity::getProjectId,project.getId());

            List<ProjectAssignments> projectAssignmentsList = projectAssignmentsMapper.selectList(projectAssignmentsQueryWrapper);
            if (projectAssignmentsList.size()>0){
                projectAssignmentsMapper.delete(projectAssignmentsQueryWrapper);//删除对应的分配表记录
            }

            List<Participant> participantList = participantMapper.selectList(participantQueryWrapper);
            if (participantList.size()>0){
                participantMapper.delete(participantQueryWrapper);//删除对应的项目参与人员
            }


            List<FileEntity> fileEntityList = fileEntityMapper.selectList(fileEntityQueryWrapper);
            if (fileEntityList.size()>0){
                for(FileEntity fileEntity : fileEntityList){
//                    Optional.ofNullable(fileEntity).ifPresent(entity -> {
//                        entity.setProjectId(null);
//                        //假删除
//                        entity.setIsDelete(FileEntity.IsDelete.deleted);//删除该项目的文件往来记录
//                        // 更新文件实体
//                        System.out.println("fileEntity.getProjectId()是："+entity.getProjectId());
//                        fileEntityMapper.updateById(entity);
//                    });
//                    假删除
                    fileEntityService.update(new UpdateWrapper<FileEntity>().lambda()
                            .set(FileEntity::getIsDelete, FileEntity.IsDelete.deleted)
                            .set(FileEntity::getProjectId,null)
                            .eq(FileEntity::getId,fileEntity.getId()));
                    //这种方式不行
//                    fileEntity.setIsDelete(FileEntity.IsDelete.deleted);//删除该项目的文件往来记录
////                    清空项目文件关联记录，否则项目删除不了
//                    fileEntity.setProjectId((long) -1);//为什么设为空，却更新不到
////                    还要把项目里的文件id清空
//                    System.out.println("fileEntity.getProjectId()是："+fileEntity.getProjectId());
//                    fileEntity.setProjectId(null);
//                    fileEntityMapper.updateById(fileEntity);
                }
            }

            //清空相关任务的项目id
            taskService.update(new UpdateWrapper<Tasks>().lambda()
                    .set(Tasks::getProjectId,null)
                    .eq(Tasks::getProjectId,project.getId()));
            //最后删除项目
            projectMapper.deleteById(project.getId());
            return true;
        }

        return false;
    }
}
